/**
 * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
 * This file is part of CSipSimple.
 *
 *  CSipSimple is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  If you own a pjsip commercial license you can also redistribute it
 *  and/or modify it under the terms of the GNU Lesser General Public License
 *  as an android library.
 *
 *  CSipSimple is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CSipSimple.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.mcptt.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.cloudptt.api.product.log.Log;

public class DBAdapter {
	//    private final static String THIS_FILE = "DBAdapter";

	private final Context context;
	private DatabaseHelper databaseHelper;

	public DBAdapter(Context aContext) {
		Log.debug(this.getClass(), "DBAdapter");
		context = aContext;
		databaseHelper = new DatabaseHelper(context);
	}

	public static class DatabaseHelper extends SQLiteOpenHelper {

		private static final int DATABASE_VERSION = 1;
		//	private static final int API_VERSION = 41;

		//閫氳褰曡〃
		private final static String TABLE_CONFIG_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.Config_Table
				+"(" 
				+ DbConst._ID	            + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ DbConst.COL_FileName	 			+ " text,"
				+ DbConst.COL_ETag 			+ " text," 
				+ DbConst.COL_ConfigContent 		+ " text,"	
				+ DbConst.COL_Date 		+ " text)";

		private final static String TABLE_GROUP_CONFIG_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.Group_Config_Table
				+"(" 
				+ DbConst._ID	            + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ DbConst.COL_GroupName	 			+ " text,"
				+ DbConst.COL_ETag 			+ " text," 
				+ DbConst.COL_ConfigContent 		+ " text,"	
				+ DbConst.COL_Date 		+ " text)";

		//鍘嗗彶璁板綍琛�
		private final static String TABLE_HIRSTORY_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.History_Table
				+"(" 
				+ DbConst._ID	            + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				//		+ DbConst.COL_ReceiverUId    + " text,"
				+ DbConst.COL_ReceiverNum	 + " text,"
				//		+ DbConst.COL_lastSenderUId  + " text," 
				+ DbConst.COL_lastSenderNum  + " text,"
				+ DbConst.COL_lastSenderName + " text,"
				+ DbConst.COL_LastMsgType + " INTEGER,"
				+ DbConst.COL_LastMsgContent + " text,"
				+ DbConst.COL_LastMsgDate    + " DATETIME DEFAULT CURRENT_TIMESTAMP," 
				+ DbConst.COL_UnreadCount    + " text,"
				+ DbConst.COL_Affiliation    + " INTEGER)";


		private final static String TABLE_HIRSTORY_DELETE =" DROP TABLE IF EXISTS "+DbConst.History_Table;

		//浼氳瘽琛�
		private final static String TABLE_SESSION_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.Session_Table
				+"(" 
				+ DbConst._ID	 			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
				//		+ DbConst.COL_ReceiverUId	+ " text,"
				+ DbConst.COL_ReceiverNum	+ " text,"
				//		+ DbConst.COL_SenderUId 		+ " text," 
				+ DbConst.COL_SenderId 		+ " text," 
				+ DbConst.COL_Content 		+ " text," 
				+ DbConst.COL_Date 			+ " DATETIME DEFAULT CURRENT_TIMESTAMP,"
				+ DbConst.COL_Direction 	+ " INTEGER," 	
				+ DbConst.COL_Len     		+ " INTEGER," 	
				+ DbConst.COL_MsgType 		+ " INTEGER,"
				+ DbConst.COL_Status     	+ " INTEGER ) ";

		private final static String TABLE_SESSION_DELETE =" DROP TABLE IF EXISTS "+DbConst.Session_Table;

		//会话表
		private final static String TABLE_MAP_POINT_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.Map_Point_Table
				+"(" 
				+ DbConst._ID	 			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
				//				+ DbConst.COL_ReceiverUId	+ " text,"
				//				+ DbConst.COL_ReceiverNum	+ " text,"
				//				+ DbConst.COL_SenderUId 		+ " text," 
				+ DbConst.COL_SenderId 		+ " text," 
				//				+ DbConst.COL_IsSendRequest 	+ " BOOLEAN," 
				+ DbConst.COL_Lattitude 		+ " DOUBLE,"
				+ DbConst.COL_Longitude     	+ " DOUBLE,"
				+ DbConst.COL_Altitude 			+ " DOUBLE," 
				+ DbConst.COL_Time			+ " LONG,"
				+ DbConst.COL_Loc_Info			+ " text,"
				+ DbConst.COL_Loc_Type			+ " INTEGER )";

		private final static String TABLE_MAP_POINT_DELETE =" DROP TABLE IF EXISTS "+DbConst.Map_Point_Table;
		
		//for location track
		private final static String TABLE_LOCATION_TRACK_CREATE = "CREATE TABLE IF NOT EXISTS "
				+ DbConst.Location_Track_Table
				+ "("
				+ DbConst._ID					+" integer primary key autoincrement,"
				+ DbConst.COL_SenderId			+" text,"
				+ DbConst.COL_Lattitude 		+ " DOUBLE,"
				+ DbConst.COL_Altitude 			+ " DOUBLE," 
				+ DbConst.COL_Longitude     	+ " DOUBLE,"
				+ DbConst.COL_Time				+ " LONG,"
				+ DbConst.COL_Valid				+ " INTEGER )";
		
//		private final static String TABLE_LOCATION_TRACK_DELETE = " DROP TABLE IF EXISTS "+DbConst.Location_Track_Table;
		
		//閫氳褰曡〃
		private final static String TABLE_ADDRESS_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.AddressList_Table
				+"(" 
				+ DbConst._ID	 			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
				//		+ DbConst.COL_UID 			+ " text, " 
				+ DbConst.COL_Type 		    + " INTEGER,"
				+ DbConst.COL_Name 			+ " text," 
				+ DbConst.COL_Id 			+ " text,"
//				+ DbConst.COL_McpttId 		+ " text,"
//				+ DbConst.COL_McvideoId 	+ " text,"
//				+ DbConst.COL_McdataId 		+ " text,"
				+ DbConst.COL_GroupId 	    + " text,"
				+ DbConst.COL_State 		+ " INTEGER,"
				+ DbConst.COL_Attr 		    + " INTEGER)";
		
		private final static String TABLE_GROUP_ADDRESS_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.GroupAddressList_Table
				+"(" 
				+ DbConst._ID	 			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
				//		+ DbConst.COL_UID 			+ " text, " 
				+ DbConst.COL_Type 		    + " INTEGER,"
				+ DbConst.COL_Name 			+ " text," 
				+ DbConst.COL_Id 			+ " text,"
				+ DbConst.COL_GroupId 		+ " text,"
				+ DbConst.COL_PGroupId 		+ " text,"
				+ DbConst.COL_State 		+ " INTEGER,"
				+ DbConst.COL_GCallTimer 	+ " INTEGER,"
				+ DbConst.COL_Attr 			+ " INTEGER)";
		
		private final static String VIEW_ADDRESS_CREATE =  "CREATE VIEW "
				+ DbConst.AddressList_View
				+" as select " 
				+ DbConst.COL_Type 		    + ","
				+ DbConst.COL_Name 			+ "," 
				+ DbConst.COL_Id 			
				+ " from " + DbConst.GroupAddressList_Table
				+" union all select distinct " 
				+ DbConst.COL_Type 		    + ","
				+ DbConst.COL_Name 			+ "," 
				+ DbConst.COL_Id 			
				+ " from " + DbConst.AddressList_Table
				+ " order by "+ DbConst.COL_Type;
		
		//缇ょ粍鎴愬憳琛�
		private final static String TABLE_MEMBER_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.MEMBER_TABLE
				+"(" 
				+ DbConst._ID	            + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ DbConst.COL_MEMBER_GROUP_NUM     + " text," 
				//		+ DbConst.COL_MEMBER_PUID    + " text,"
				+ DbConst.COL_MEMBER_NUM     + " text,"
				+ DbConst.COL_MEMBER_NAME    + " text,"
				+ DbConst.COL_MEMBER_PRIORITY + " INTEGER,"
				+ DbConst.COL_MEMBER_STATUS  + " text)";
		
		private final static String TABLE_LOGIN_CREATE =  "CREATE TABLE IF NOT EXISTS "
				+ DbConst.LoginState_Table
				+"(" 
				+ DbConst._ID	            + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ DbConst.COL_SenderId 	+ " text,"
				+ DbConst.COL_Ip	+ " text,"
				+ DbConst.COL_State		    + " INTEGER)";
		
//		private final static String TABLE_LOGIN_DELETE = " DROP TABLE IF EXISTS "+DbConst.LoginState_Table;


		DatabaseHelper(Context context) {
			super(context, DbConst.AUTHORITY, null, DATABASE_VERSION);
			Log.debug(this.getClass(), "DatabaseHelper new ");
		}

		@Override
		public void onCreate(SQLiteDatabase db) 
		{
			Log.debug(this.getClass(), "DatabaseHelper onCreate ");
			final int version = db.getVersion();
			Log.debug(this.getClass(), "onCreate version = " + version);
			db.execSQL(TABLE_CONFIG_CREATE);
			db.execSQL(TABLE_GROUP_CONFIG_CREATE);
			db.execSQL(TABLE_ADDRESS_CREATE);
			db.execSQL(TABLE_GROUP_ADDRESS_CREATE);
			db.execSQL(VIEW_ADDRESS_CREATE);
			db.execSQL(TABLE_SESSION_CREATE);
			db.execSQL(TABLE_MAP_POINT_CREATE);
			db.execSQL(TABLE_LOCATION_TRACK_CREATE);
			db.execSQL(TABLE_HIRSTORY_CREATE);
			db.execSQL(TABLE_MEMBER_CREATE);
			db.execSQL(TABLE_LOGIN_CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.debug(this.getClass(), "Upgrading database from version "
					+ oldVersion + " to " + newVersion);
			//			onCreate(db);
			//	    if(oldVersion < API_VERSION)
			//	    {
			//		Log.debug(this.getClass(), "Upgrading begin");
			//		db.execSQL(TABLE_HIRSTORY_DELETE);
			//		db.execSQL(TABLE_HIRSTORY_CREATE);
			//		db.execSQL(TABLE_SESSION_DELETE);
			//		db.execSQL(TABLE_SESSION_CREATE);
			//		Log.debug(this.getClass(), "Upgrading end");
			//	    }
		}
	}

	private boolean opened = false;
	/**
	 * Open database
	 * 
	 * @return database adapter
	 * @throws SQLException
	 */
	public DBAdapter open() throws SQLException {
		databaseHelper.getWritableDatabase();
		opened = true;
		return this;
	}

	/**
	 * Close database
	 */
	public void close() {
		databaseHelper.close();
		opened = false;
	}

	public boolean isOpen() {
		return opened;
	}
}
